const api = require('../../utils/api')
const { networkHelper } = require('../../utils/network-helper')
const { safeGet, validateOrder, completeOrder } = require('../../utils/data-validator')
const app = getApp()

Page({
  data: {
    testResults: [],
    isLoading: false,
    networkStatus: {},
    mockOrder: {
      storeId: 1,
      items: [
        { productId: 1, name: '测试商品', price: 25.5, quantity: 2 }
      ],
      totalAmount: 51.0,
      orderType: 'delivery',
      deliveryAddress: '测试地址'
    }
  },

  onLoad() {
    this.checkNetworkStatus()
    this.addToCart() // 为测试添加购物车商品
  },

  // 检查网络状态
  async checkNetworkStatus() {
    const status = await networkHelper.checkNetworkStatus()
    this.setData({ networkStatus: status })
    
    // 显示网络提示
    if (!status.isOnline) {
      wx.showToast({
        title: '网络未连接，将使用模拟模式',
        icon: 'none',
        duration: 3000
      })
    }
  },

  // 添加测试商品到购物车
  addToCart() {
    app.addToCart({
      id: 1,
      name: '测试汉堡',
      price: 25.5,
      imageUrl: '/images/products/test.jpg'
    }, 1)
  },

  // 测试创建订单
  async testCreateOrder() {
    this.addTestResult('开始测试创建订单...')
    this.setData({ isLoading: true })

    try {
      const orderData = {
        storeId: 1,
        items: this.data.mockOrder.items,
        totalAmount: this.data.mockOrder.totalAmount,
        orderType: 'delivery',
        deliveryAddress: '北京市朝阳区测试地址123号',
        contactPhone: '13800138000',
        remark: '测试订单'
      }

      // 使用网络助手包装API请求
      const result = await networkHelper.apiRequest(
        () => api.createOrder(orderData),
        {
          fallbackData: {
            code: 200,
            message: '订单创建成功(模拟)',
            data: {
              id: Date.now(),
              orderNo: 'TEST' + Date.now(),
              status: 'PENDING_PAYMENT',
              ...orderData
            }
          }
        }
      )

      this.addTestResult(`✅ 创建订单成功: ${result.data.orderNo}`)
      
      // 测试支付流程
      await this.testPayment(result.data.id, result.data.totalAmount)

    } catch (error) {
      this.addTestResult(`❌ 创建订单失败: ${error.message}`)
    }

    this.setData({ isLoading: false })
  },

  // 测试支付流程
  async testPayment(orderId, amount) {
    this.addTestResult('开始测试支付流程...')

    try {
      const payment = require('../../utils/payment')
      
      const result = await payment.processPayment(orderId, amount, 'wechat')
      
      if (result.success) {
        this.addTestResult(`✅ 支付成功: ${result.data.paymentId}`)
        
        // 更新订单状态
        this.updateOrderStatus(orderId, 'PAID')
      } else {
        this.addTestResult(`❌ 支付失败: ${result.message}`)
      }

    } catch (error) {
      this.addTestResult(`❌ 支付异常: ${error.message}`)
    }
  },

  // 更新订单状态
  updateOrderStatus(orderId, status) {
    const localOrders = wx.getStorageSync('mockOrders') || []
    const orderIndex = localOrders.findIndex(order => order.id === orderId)
    
    if (orderIndex !== -1) {
      localOrders[orderIndex].status = status
      localOrders[orderIndex].updatedAt = new Date().toISOString()
      wx.setStorageSync('mockOrders', localOrders)
      this.addTestResult(`📝 订单状态更新: ${status}`)
    }
  },

  // 测试订单查询
  async testOrderQuery() {
    this.addTestResult('开始测试订单查询...')

    try {
      // 使用网络助手测试真实API调用
      const userId = app.getSafeUserId()
      this.addTestResult(`📋 使用用户ID: ${userId}`)
      
      const result = await networkHelper.apiRequest(
        () => api.getUserOrders(userId),
        {
          fallbackData: [],
          showOfflineMessage: false
        }
      )
      
      if (result && result.code === 200) {
        const orders = result.data.orders || result.data || []
        this.addTestResult(`✅ API调用成功，获取到 ${orders.length} 个订单`)
      } else if (Array.isArray(result)) {
        this.addTestResult(`🔄 使用降级数据，获取到 ${result.length} 个订单`)
      } else {
        this.addTestResult('📝 暂无订单数据')
      }
      
      // 获取本地订单
      const localOrders = wx.getStorageSync('mockOrders') || []
      if (localOrders.length > 0) {
        const latestOrder = localOrders[localOrders.length - 1]
        this.addTestResult(`📱 本地存储订单: ${latestOrder.orderNo}`)
        this.addTestResult(`   状态: ${latestOrder.status}`)
        this.addTestResult(`   金额: ¥${latestOrder.totalAmount}`)
      }

    } catch (error) {
      this.addTestResult(`❌ 查询订单失败: ${error.message}`)
    }
  },

  // 测试数据验证工具
  testDataValidation() {
    this.addTestResult('开始测试数据验证工具...')

    try {
      // 测试1：正常订单验证
      const validOrder = {
        id: 1,
        orderNo: 'TEST001',
        status: 'COMPLETED',
        totalAmount: '99.99',
        store: {
          id: 1,
          name: '测试商家',
          phone: '010-12345678'
        },
        items: [
          { productId: 1, name: '测试商品', price: 99.99, quantity: 1 }
        ]
      }

      const validation1 = validateOrder(validOrder)
      this.addTestResult(`✅ 正常订单验证: ${validation1.isValid ? '通过' : '失败'}`)
      if (validation1.warnings.length > 0) {
        this.addTestResult(`   警告: ${validation1.warnings.join(', ')}`)
      }

      // 测试2：缺失字段的订单
      const incompleteOrder = {
        id: 2,
        status: 'PENDING'
        // 缺少很多必要字段
      }

      const validation2 = validateOrder(incompleteOrder)
      this.addTestResult(`⚠️ 不完整订单验证: ${validation2.isValid ? '通过' : '失败'}`)
      if (validation2.errors.length > 0) {
        this.addTestResult(`   错误: ${validation2.errors.slice(0, 3).join(', ')}...`)
      }

      // 测试3：数据补全功能
      const completedOrder = completeOrder(incompleteOrder)
      this.addTestResult(`🔧 数据补全测试: 成功`)
      this.addTestResult(`   补全后商家: ${safeGet(completedOrder, 'store.name', '未知')}`)
      this.addTestResult(`   补全后电话: ${safeGet(completedOrder, 'store.phone', '无')}`)

      // 测试4：safeGet安全访问
      const testObj = { a: { b: { c: 'deep value' } } }
      const safeValue1 = safeGet(testObj, 'a.b.c', 'default')
      const safeValue2 = safeGet(testObj, 'x.y.z', 'default')
      const safeValue3 = safeGet(null, 'any.path', 'default')

      this.addTestResult(`🛡️ SafeGet测试: 深度访问=${safeValue1}`)
      this.addTestResult(`   不存在路径=${safeValue2}`)
      this.addTestResult(`   空对象访问=${safeValue3}`)

      this.addTestResult('✨ 数据验证工具测试完成!')

    } catch (error) {
      this.addTestResult(`❌ 数据验证测试失败: ${error.message}`)
    }
  },

  // 清空测试数据
  clearTestData() {
    wx.showModal({
      title: '确认清空',
      content: '将清空所有测试订单数据',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('mockOrders')
          app.clearCart()
          this.setData({ testResults: [] })
          this.addTestResult('🗑️ 测试数据已清空')
        }
      }
    })
  },

  // 运行完整流程测试
  async runFullTest() {
    this.setData({ testResults: [] })
    this.addTestResult('🚀 开始完整流程测试...')
    
    // 检查网络
    await this.checkNetworkStatus()
    
    // 测试创建订单（包含支付）
    await this.testCreateOrder()
    
    // 等待一秒
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 测试订单查询
    await this.testOrderQuery()
    
    this.addTestResult('✨ 完整流程测试完成!')
  },

  // 添加测试结果
  addTestResult(message) {
    const timestamp = new Date().toLocaleTimeString()
    const result = `[${timestamp}] ${message}`
    
    this.setData({
      testResults: [...this.data.testResults, result]
    })
    
    console.log(result)
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '小程序订单测试',
      path: '/pages/test-order/test-order'
    }
  }
}) 